import {Component, ViewChild} from '@angular/core';
import {UserService} from "../../../user/service/user.service";
import {UserEntity} from "../../../user/model/userEntity";
import {PromptService} from "../../../util/prompt/prompt.service";
import {Router} from "@angular/router";
import {CommonService} from "../../../util/common.service";
import {CurrentUserInfo} from "../../../user/model/currentUserInfo";
import {NavigationBarService} from "../../service/navigationBar.service";
import {UserEditForm} from "../../../user/model/userEditForm";


declare var $: any;
@Component({
    moduleId: module.id,
    selector: 'head-component',
    templateUrl: "./head.html"
})
export class HeadComponent {

    @ViewChild("changePasswordModal") changePasswordModal: any
    currentUser: CurrentUserInfo = new CurrentUserInfo();
    navigationBar: string = "首页"
    userEditForm: UserEditForm = new UserEditForm()

    constructor(private userService: UserService, private promptService: PromptService, private router: Router, public commonService: CommonService, private navigationBarService: NavigationBarService) {
        navigationBarService.missionAnnounced$.subscribe(
            str => {
                this.navigationBar = str
            });
    }


    logout() {
        this.userService.logout().then((data: any)=> {
            if (data.success) {
                this.promptService.info(data.result)
                this.userService.clearCurrentUserInfo()
                this.router.navigate(["/login"]);
            }
        })
    }

    ngOnInit() {
        this.userService.getCurrentUserInfo().then((data: CurrentUserInfo)=> {
            this.currentUser = data;
            // console.log(this.currentUser)
        })

    }


    changePassword() {
        if (this.userEditForm.password == undefined || this.userEditForm.password == "") {
            this.promptService.warning("请输入新密码")
            return false
        }

        if (this.userEditForm.repassword == undefined || this.userEditForm.repassword == "") {
            this.promptService.warning("请输入确认密码")
            return false
        }

        if (this.userEditForm.password != this.userEditForm.repassword) {
            this.promptService.warning("两次密码不一致")
            return false
        }

        this.userService.changeUserPassword(this.userEditForm).then((data)=>{
            if (data.success) {
                this.promptService.info(data.result)
                this.commonService.hideModal(this.changePasswordModal)
            } else {
                this.promptService.warning(data.error.message)
            }
        })
    }

    showChangePasswordModal() {
        this.userEditForm = new UserEditForm();
        this.commonService.showModal(this.changePasswordModal)
    }
}